package com.zyylc.wine.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtil {

	private static final String DEFAULT_KEY = "ihopeyouneverknowit";

	/**
	 * @param content
	 *            待加密内容
	 * @return 加密后的内容是用BASE64编码
	 */
	public final static String encrypt(String content) {
		try {
			return new BASE64Encoder().encode(encrypt(content, DEFAULT_KEY));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @param data
	 *            待解密内容 （被Base64编码过的）
	 * @return 解密后的内容
	 */
	public final static String decrypt(String data) {
		try {
			return new String(decrypt(new BASE64Decoder().decodeBuffer(data), DEFAULT_KEY));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            待加密内容
	 * @param key
	 *            加密的密钥
	 * @return
	 */
	public static byte[] encrypt(String content, String key) {
		try {
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			byte[] result = cipher.doFinal(content.getBytes());
			return result;
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 解密
	 * 
	 * @param data
	 *            待解密内容
	 * @param key
	 *            解密的密钥
	 * @return
	 */
	public static String decrypt(byte[] data, String key) {
		try {
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, securekey, random);
			byte[] result = cipher.doFinal(data);
			return new String(result);
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
	}
}
